<?php
/**
 * Created by PhpStorm.
 * Author: huangwy
 * Date: 2018/3/15 16:16
 * Version: 1.0
 */
namespace app\admin\controller;

use app\admin\logic\WechatLogic;
use think\Db;
use app\common\logic\wechat\WechatUtil;
use app\common\logic\WechatCommonLogic;
use app\common\model\WxNews;
use app\common\model\WxReply;
use app\common\model\WxTplMsg;
use app\common\model\WxMaterial;
class WxManage extends Base {
    /**
     * 微信信息设置
     */
    private $wx_info;

    function __construct()
    {
        parent::__construct();
        $this->wx_info = db('wx_info')->find();
    }


    /**
     * 微信配置页面
     * @return \think\response\View
     */
    public function setting(){
        //获取微信设置信息
        $wx_info = $this->wx_info;
        if($wx_info['id']){
            $apiurl = 'http://' . $_SERVER['HTTP_HOST'] . '/index.php/Weixin/index';

            $this->assign('wxSetting',$wx_info);
            $this->assign('apiurl',$apiurl);
        }
        return view();
    }

    /**
     * 更新微信配置信息
     */
    public function updateWxchat(){
        $data = input();
        db('wx_info')->where('id',$data['id'])->update($data);
        return json(['flag'=>0,'message'=>'恭喜，修改微信配置成功！']);
    }



    /**
     * 微信栏目
     */
    public function menu(){
        $option = db('wx_menu')->select();
        $option = getMenu($option,'menu_id','parentid');
        $this->assign('list',$option);
        return view('index');
    }

    /**
     * 添加页面
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add(){
        //查询一级栏目
        $option = db('wx_menu')->where('parentid=0 and status=1')->select();
        $this->assign('wxoption',$option);
        return view('form');
    }

    public function edit(){
        $id = input('id');
        //查询一级栏目
        $option = db('wx_menu')->where('parentid=0 and status=1')->select();
        //查询对应信息
        $wxmenu = db('wx_menu')->where('menu_id',$id)->find();
        $this->assign('wxoption',$option);
        $this->assign('wxmenu',$wxmenu);
        return view('form');
    }
    public function del()
    {
        $ids = input('ids');
        $wechatLogic = new WechatLogic();
        $del = $wechatLogic->wxMenuDel($ids);
        if ($del) {
            if($del['flag'] == 0){
                return json(['flag'=>0,'message'=>$del['message']]);
            }else{
                $del = '恭喜，菜单删除成功！';
                return json(['flag'=>0,'message'=>$del]);
            }

        } else {
            return json(['flag'=>0,'message'=>'操作失败！']);
        }
    }

    /**
     * @return \think\response\Json
     */
    public function update(){
        $info = input('post.');
        $wechatLogic = new WechatLogic();
        $update = $wechatLogic->wxMenuUpdate($info);
        if ($update) {
            $update = is_string($update)?$update:'操作成功！';
            return json(['flag'=>0,'message'=>$update]);
        }else{
            return json(['flag'=>0,'message'=>'操作失败！']);
        }
    }

    public function setMenu(){
        $Model = db('wx_menu');
        $where['status'] = 1;

        $list = $Model->where($where)->select();
        $memu = $this->memuJson($list);

        $wechatObj = new WechatUtil($this->wx_user);
        if ($wechatObj->createMenu($memu) === false) {
            $this->error($wechatObj->getError());
        }else{
            $this->success('更新菜单成功!');
        }
    }


    /**
     * 返回单菜单结构
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    private function memuJson($data=''){
        if(!$data){
            return false;
        }
        foreach ($data as $rs) {
            $plist[$rs['parentid']][] = $rs;
        }
        $jsonlist = array();
        foreach ($plist[0] as $rs) {
            $memu = $plist[$rs['menu_id']];
            //有二级栏目
            if($memu){
                $json['name'] = $rs['name'];
                $sub_button = array();
                foreach ($memu as $row) {
                    $sub_button[] = $this->memuOne($row);
                }
                $json['sub_button'] = $sub_button;
            }else{
                $json = $this->memuOne($rs);
            }
            $jsonlist[] = $json;
        }
        $button['button'] = $jsonlist;
        return json_encode($button,JSON_UNESCAPED_UNICODE);
    }
    private function memuOne($data){
        $type = 'click';
        $key  = '';
        //触发关键字
        if($data['type']==1){
            $key = $data['key'];
        }
        //URL
        if($data['type']==2){
            $type = 'view';
        }

        $memu['name'] = $data['name'];
        $memu['type'] = $type;
        if($type=='view'){
            $memu['url'] = $data['url'];
        }else{
            $memu['key'] = $key;
        }
        return $memu;
    }


    /**
     * 默认回复、关注自动回复 default/follow
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function auto_reply_edit(){
        $id = input('id/d');
        $type = input('type', WxReply::TYPE_KEYWORD);
        $types = $this->auto_reply_menu();

        if (!key_exists($type, $types)) {
            $this->error("标签 $type 不存在");
        }

        if ($type == WxReply::TYPE_KEYWORD) {
            if ($id && !$reply = WxReply::get(['id' => $id, 'type' => $type])) {
                $this->error('该自动回复不存在');
            }
        } else {
            $reply = WxReply::get(['type' => $type]);
        }


        //新闻类，待定暂无
        if  ( ! empty($reply)) {
            if ($reply->msg_type == WxReply::MSG_NEWS) {
                $news = WxMaterial::get($reply->material_id, 'wxNews');
                $this->assign('news', $news);
            }
            $this->assign('reply', $reply);
        }


        $this->assign('type', $type);
        $this->assign('types', $types);

        return $this->fetch();
    }

    /**
     * 关键字回复
     */
    public function keyword_reply()
    {
        $type = input('type', WxReply::TYPE_KEYWORD);
        $types = $this->auto_reply_menu();
        if (!key_exists($type, $types)) {
            $this->error("标签 $type 不存在");
        }
        $this->assign('type', $type);
        $this->assign('types', $types);

        if ($type == WxReply::TYPE_KEYWORD) {

            $condition = ['type' => $type];
            $replies = WxReply::where($condition)->with('wxKeywords')->order('id', 'asc')->paginate(10,false,['query'=>request()->param()]);
            $this->assign('list', $replies);
            return $this->fetch();

        } else {
            $this->redirect('auto_reply_edit', ['type' => $type]);
        }
    }

    /**
     * 消息自动回复
     */

    /**
     * 自动回复的菜单
     */
    private function auto_reply_menu()
    {
        return [
            WxReply::TYPE_KEYWORD => ['menu' => '关键词自动回复', 'url' => url('keyword_reply', ['type' => WxReply::TYPE_KEYWORD])],
            WxReply::TYPE_DEFAULT => ['menu' => '消息自动回复', 'url' => url('auto_reply_edit', ['type' => WxReply::TYPE_DEFAULT])],
            WxReply::TYPE_FOLLOW  => ['menu' => '关注时自动回复', 'url' => url('auto_reply_edit', ['type' => WxReply::TYPE_FOLLOW])]
        ];
    }

    /**
     * 新增自动回复
     */
    public function add_auto_reply()
    {
        $type = input('msg_type');
        $data = input('post.');
        $logic = new WechatCommonLogic($this->wx_info);
        $return = $logic->addAutoReply($type, $data);
        if($return['status'] ==0){
            return json(['flag'=>0,'message'=>'配置成功']);
        }else{
            return json(['flag'=>-1,'message'=>$return['msg']]);
        }

    }

    /**
     * 更新自动回复
     */
    public function update_auto_reply()
    {
        $type = input('msg_type');
        $id = input('id/d', 0);
        $data = input('post.');
        $logic = new WechatCommonLogic($this->wx_info);
        $return = $logic->updateAutoReply($type, $id, $data);
        if($return['status'] ==0){
            return json(['flag'=>0,'message'=>'修改配置成功']);
        }else{
            return json(['flag'=>-1,'message'=>$return['msg']]);
        }
    }
}
